<template>
  <div class="articles-container">
    <div class="articles-header">
      <h1 class="page-title">
        <i class="bi bi-file-text me-2"></i>
        文章管理
      </h1>
      <p class="page-subtitle">管理网站文章和内容发布</p>
    </div>

    <div class="articles-content">
      <!-- 操作栏（Element Plus） -->
      <div class="header-section">
        <div class="search-section">
          <el-input v-model="searchQuery" placeholder="搜索文章标题或内容..." clearable class="w-300 mr-16">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select v-model="selectedCategory" placeholder="全部分类" clearable class="w-150 mr-16">
            <el-option label="全部分类" value="" />
            <el-option label="技术" value="技术" />
            <el-option label="新闻" value="新闻" />
            <el-option label="教程" value="教程" />
            <el-option label="博客" value="博客" />
          </el-select>

          <el-select v-model="selectedStatus" placeholder="全部状态" clearable class="w-120 mr-16">
            <el-option label="全部状态" value="" />
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </div>

        <el-button type="primary" :icon="Plus" @click="showCreateDialog = true">写文章</el-button>
      </div>

      <!-- 文章列表 -->
      <div class="card shadow">
        <div class="card-body">
          <div class="table-responsive">
            <el-table :data="displayedArticles" stripe style="width: 100%" empty-text="暂无数据">
              <el-table-column label="标题" min-width="240">
                <template #default="{ row }">
                  <div class="article-info">
                    <div class="article-title">{{ row.title }}</div>
                    <div class="article-summary">
                      <el-text type="info" size="small">{{ row.summary }}</el-text>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="分类" width="120" align="center">
                <template #default="{ row }">
                  <el-tag type="info" size="small">{{ row.category }}</el-tag>
                </template>
              </el-table-column>

              <el-table-column label="作者" min-width="160">
                <template #default="{ row }">
                  <div class="author-info">
                    <div class="author-name">{{ row.author.name }}</div>
                    <div class="author-email">
                      <el-text type="info" size="small">{{ row.author.email }}</el-text>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="状态" width="120" align="center">
                <template #default="{ row }">
                  <el-tag
                    :type="row.status === 'published' ? 'success' : row.status === 'draft' ? 'warning' : 'info'"
                    size="small"
                  >
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="阅读量" width="120" align="center">
                <template #default="{ row }">
                  <el-text type="primary">{{ row.views }}</el-text>
                </template>
              </el-table-column>

              <el-table-column label="发布时间" width="180" align="center">
                <template #default="{ row }">
                  {{ formatDate(row.publishedAt || row.createdAt) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" width="260" align="center" fixed="right">
                <template #default="{ row }">
                  <div class="action-cell">
                    <el-button size="small" @click="editArticle(row)">编辑</el-button>
                    <el-button size="small" @click="viewArticle(row)">预览</el-button>
                    <el-button
                      v-if="row.status === 'draft'"
                      size="small"
                      type="success"
                      @click="publishArticle(row.id)"
                    >
                      发布
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteArticle(row.id)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-section">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 创建文章对话框（Element Plus） -->
    <el-dialog v-model="showCreateDialog" title="写文章" width="800px">
      <el-form label-width="90px">
        <el-form-item label="标题">
          <el-input v-model="createForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="createForm.category" placeholder="选择分类">
            <el-option label="技术" value="技术" />
            <el-option label="新闻" value="新闻" />
            <el-option label="教程" value="教程" />
            <el-option label="博客" value="博客" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="createForm.tags" placeholder="请输入标签，用逗号分隔" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="createForm.summary" type="textarea" :rows="3" placeholder="请输入文章摘要" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="createForm.content" type="textarea" :rows="10" placeholder="请输入文章内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitCreate">发布文章</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";

defineOptions({
  name: "ArticlesView",
});

// 响应式数据
const searchQuery = ref("");
const selectedCategory = ref("");
const selectedStatus = ref("");
const showCreateDialog = ref(false);

// 写文章表单
const createForm = ref({
  title: "",
  category: "技术",
  tags: "",
  summary: "",
  content: "",
});

const resetCreateForm = () => {
  createForm.value = {
    title: "",
    category: "技术",
    tags: "",
    summary: "",
    content: "",
  };
};

const submitCreate = () => {
  if (!createForm.value.title.trim()) {
    ElMessage.warning("请输入文章标题");
    return;
  }
  const now = new Date().toISOString();
  const nextId = articles.value.length > 0 ? Math.max(...articles.value.map((a: any) => a.id)) + 1 : 1;

  articles.value.unshift({
    id: nextId,
    title: createForm.value.title.trim(),
    summary:
      createForm.value.summary?.trim() ||
      (createForm.value.content ? createForm.value.content.slice(0, 60) + "…" : "暂无摘要"),
    category: createForm.value.category,
    author: {
      name: "当前用户",
      email: "user@example.com",
    },
    status: "published",
    views: 0,
    createdAt: now,
    publishedAt: now,
  });

  showCreateDialog.value = false;
  ElMessage.success("发布成功");
  resetCreateForm();

  // 重新计算分页总数并回到第一页
  pagination.value.total = filteredArticles.value.length;
  pagination.value.page = 1;
};

// 模拟文章数据
const articles = ref(
  Array.from({ length: 40 }).map((_, i) => {
    const categories = ["技术", "新闻", "教程", "博客"];
    const statuses = ["published", "draft", "archived"];
    const category = categories[i % categories.length];
    const status = statuses[i % statuses.length];
    const baseDate = new Date(Date.now() - Math.random() * 1000 * 60 * 60 * 24 * 60); // 近两个月随机
    return {
      id: i + 1,
      title: `示例文章标题 ${i + 1}`,
      summary: "这是一段示例摘要，用于展示筛选与分页效果……",
      category,
      author: {
        name: `作者${(i % 8) + 1}`,
        email: `author${(i % 8) + 1}@example.com`,
      },
      status,
      views: Math.floor(Math.random() * 5000),
      createdAt: baseDate.toISOString(),
      publishedAt: status === "published" ? new Date(baseDate.getTime() + 3600_000).toISOString() : null,
    };
  }),
);

// 计算属性
const filteredArticles = computed(() => {
  return articles.value.filter((article) => {
    const matchesSearch =
      article.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      article.summary.toLowerCase().includes(searchQuery.value.toLowerCase());
    const matchesCategory = !selectedCategory.value || article.category === selectedCategory.value;
    const matchesStatus = !selectedStatus.value || article.status === selectedStatus.value;
    return matchesSearch && matchesCategory && matchesStatus;
  });
});

// 本地分页状态
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 当前页数据
const displayedArticles = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize;
  return filteredArticles.value.slice(start, start + pagination.value.pageSize);
});

// 监听过滤结果更新总数并重置页码
watch(filteredArticles, (list) => {
  pagination.value.total = list.length;
  pagination.value.page = 1;
});

// 分页事件
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.page = 1;
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
};

// 方法
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString("zh-CN");
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    published: "已发布",
    draft: "草稿",
    archived: "已归档",
  };
  return statusMap[status] || status;
};

const editArticle = (article: any) => {
  console.log("编辑文章:", article);
};

const viewArticle = (article: any) => {
  console.log("预览文章:", article);
};

const publishArticle = (id: number) => {
  const article = articles.value.find((a) => a.id === id);
  if (article) {
    article.status = "published";
    article.publishedAt = new Date().toISOString();
    console.log("发布文章:", id);
  }
};

const deleteArticle = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这篇文章吗？", "提示", {
      type: "warning",
      confirmButtonText: "删除",
      cancelButtonText: "取消",
    });
    articles.value = articles.value.filter((a) => a.id !== id);
    ElMessage.success("已删除");
  } catch {
    // 用户取消删除
  }
};

onMounted(() => {
  console.log("文章管理页面加载完成");
});
</script>

<style scoped>
.articles-container {
  padding: 2rem;
  background-color: #f8f9fc;
  min-height: 100vh;
}

.articles-header {
  margin-bottom: 2rem;
}

.page-title {
  color: #5a5c69;
  font-size: 1.75rem;
  font-weight: 400;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  color: #858796;
  margin-bottom: 0;
}

.article-info {
  min-width: 300px;
}

.article-title {
  font-weight: 600;
  color: #5a5c69;
  margin-bottom: 0.25rem;
}

.article-summary {
  font-size: 0.85rem;
  line-height: 1.4;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.author-info {
  min-width: 120px;
}

.author-name {
  font-weight: 600;
  color: #5a5c69;
}

.card {
  border: none;
  border-radius: 0.35rem;
}

.shadow {
  box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;
}

.modal.show {
  background-color: rgba(0, 0, 0, 0.5);
}

.btn-group .btn {
  margin-right: 0.25rem;
}

.btn-group .btn:last-child {
  margin-right: 0;
}
.action-cell {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
}
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-light);
}
</style>
